package com.lujieni.springboothutool.config;

import com.lujieni.springboothutool.properties.WebProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 springboot2.0以上推荐实现WebMvcConfigurer接口
 */
@EnableConfigurationProperties(WebProperties.class)
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Autowired
    private WebProperties webProperties;

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurePathMatch(configurer, webProperties.getAdminApi());
    }

    /**
     * 设置 API 前缀，仅仅匹配 controller 包下的
     *
     * @param configurer 配置
     * @param api        API 配置
     */
    private void configurePathMatch(PathMatchConfigurer configurer, WebProperties.Api api) {
        // 配置点号作为路径分割符否则下面会匹配失败
        AntPathMatcher antPathMatcher = new AntPathMatcher(".");
        // clazz.isAnnotationPresent(RestController.class) 是一个用于检查某个类（clazz 所表示的类）上是否存在RestController注解
        configurer.addPathPrefix(api.getPrefix(), clazz -> clazz.isAnnotationPresent(RestController.class)
                && antPathMatcher.match(api.getController(), clazz.getPackage().getName())); // 仅仅匹配 controller 包
    }


}
